// 参考图片管理器
// 负责获取、缓存和管理参考图片

const REFERENCE_IMAGE_URL = 'http://123.56.17.253:9090/2411a-group-three/article/1eaf7de8-6dc8-43d0-9838-411cbd1f975b.jpg';
const CACHE_KEY = 'reference_image_base64';
const CACHE_TIMESTAMP_KEY = 'reference_image_timestamp';
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24小时缓存

class ReferenceImageManager {
  /**
   * 获取参考图片的Base64编码
   * @returns {Promise<string>} 参考图片的Base64编码
   */
  static async getReferenceImageBase64() {
    try {
      // 1. 先检查本地缓存
      const cachedImage = this.getCachedReferenceImage();
      if (cachedImage) {
        console.log('✅ 使用缓存的参考图片');
        return cachedImage;
      }

      // 2. 从网络获取参考图片
      console.log('📥 从网络获取参考图片...');
      const base64Image = await this.fetchReferenceImageFromNetwork();
      
      // 3. 保存到本地缓存
      this.saveReferenceImageToCache(base64Image);
      
      console.log('✅ 参考图片获取并缓存成功');
      return base64Image;
      
    } catch (error) {
      console.error('❌ 获取参考图片失败:', error);
      throw new Error('获取参考图片失败: ' + error.message);
    }
  }

  /**
   * 从网络获取参考图片
   * @returns {Promise<string>} 参考图片的Base64编码
   */
  static fetchReferenceImageFromNetwork() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: REFERENCE_IMAGE_URL,
        method: 'GET',
        responseType: 'arraybuffer',
        timeout: 30000,
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              // 将ArrayBuffer转换为Base64
              const base64 = wx.arrayBufferToBase64(res.data);
              console.log('📸 参考图片获取成功，大小:', base64.length, '字符');
              resolve(base64);
            } catch (error) {
              console.error('❌ 转换Base64失败:', error);
              reject(new Error('图片格式转换失败'));
            }
          } else {
            console.error('❌ 获取参考图片失败，HTTP状态码:', res.statusCode);
            reject(new Error(`HTTP ${res.statusCode}: 获取参考图片失败`));
          }
        },
        fail: (error) => {
          console.error('❌ 网络请求失败:', error);
          reject(new Error('网络请求失败: ' + error.errMsg));
        }
      });
    });
  }

  /**
   * 获取缓存的参考图片
   * @returns {string|null} 缓存的Base64图片或null
   */
  static getCachedReferenceImage() {
    try {
      const cachedImage = wx.getStorageSync(CACHE_KEY);
      const timestamp = wx.getStorageSync(CACHE_TIMESTAMP_KEY);
      
      if (cachedImage && timestamp) {
        const now = Date.now();
        const cacheAge = now - timestamp;
        
        if (cacheAge < CACHE_DURATION) {
          console.log('📦 使用缓存图片，缓存时间:', Math.round(cacheAge / 1000 / 60), '分钟前');
          return cachedImage;
        } else {
          console.log('⏰ 缓存已过期，需要重新获取');
          this.clearCache();
        }
      }
      
      return null;
    } catch (error) {
      console.error('❌ 读取缓存失败:', error);
      return null;
    }
  }

  /**
   * 保存参考图片到缓存
   * @param {string} base64Image Base64编码的图片
   */
  static saveReferenceImageToCache(base64Image) {
    try {
      const timestamp = Date.now();
      wx.setStorageSync(CACHE_KEY, base64Image);
      wx.setStorageSync(CACHE_TIMESTAMP_KEY, timestamp);
      console.log('💾 参考图片已保存到本地缓存');
    } catch (error) {
      console.error('❌ 保存缓存失败:', error);
    }
  }

  /**
   * 清除参考图片缓存
   */
  static clearCache() {
    try {
      wx.removeStorageSync(CACHE_KEY);
      wx.removeStorageSync(CACHE_TIMESTAMP_KEY);
      console.log('🗑️ 参考图片缓存已清除');
    } catch (error) {
      console.error('❌ 清除缓存失败:', error);
    }
  }

  /**
   * 预加载参考图片
   * @returns {Promise<boolean>} 预加载是否成功
   */
  static async preloadReferenceImage() {
    try {
      console.log('🚀 开始预加载参考图片...');
      await this.getReferenceImageBase64();
      console.log('✅ 参考图片预加载完成');
      return true;
    } catch (error) {
      console.error('❌ 参考图片预加载失败:', error);
      return false;
    }
  }

  /**
   * 获取缓存状态信息
   * @returns {Object} 缓存状态信息
   */
  static getCacheStatus() {
    try {
      const cachedImage = wx.getStorageSync(CACHE_KEY);
      const timestamp = wx.getStorageSync(CACHE_TIMESTAMP_KEY);
      
      if (cachedImage && timestamp) {
        const now = Date.now();
        const cacheAge = now - timestamp;
        const isExpired = cacheAge >= CACHE_DURATION;
        
        return {
          hasCache: true,
          isExpired: isExpired,
          cacheAge: cacheAge,
          cacheAgeMinutes: Math.round(cacheAge / 1000 / 60),
          imageSize: cachedImage.length
        };
      }
      
      return {
        hasCache: false,
        isExpired: false,
        cacheAge: 0,
        cacheAgeMinutes: 0,
        imageSize: 0
      };
    } catch (error) {
      console.error('❌ 获取缓存状态失败:', error);
      return {
        hasCache: false,
        isExpired: false,
        cacheAge: 0,
        cacheAgeMinutes: 0,
        imageSize: 0,
        error: error.message
      };
    }
  }

  /**
   * 强制刷新参考图片
   * @returns {Promise<string>} 新的参考图片Base64编码
   */
  static async refreshReferenceImage() {
    console.log('🔄 强制刷新参考图片...');
    this.clearCache();
    return await this.getReferenceImageBase64();
  }
}

module.exports = ReferenceImageManager;


